//
//  WPReadingTableViewController.m
//  wobingwoyi
//
//  Created by WGP on 16/7/21.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPReadingViewController.h"
#import "WPReadingView.h"
#import "WPReadingInvidialRanking.h"
#import "WPReadingFirstCollectionViewCell.h"
#import "WPReadingSecondCollectionViewCell.h"
#import "WPMRModel.h"
#import "WPCoinTopUp.h"
#import "WPSearchVC.h"
#import "WPPanNavigationController.h"
#import "WPReadingViewCollectionViewCell.h"
#import "WPReadingViewCollectionViewCellVC.h"
#import "WPReadingViewCollectionViewChargeCellVC.h"
#import "WPTitleView.h"
#import "WPNewDiseaseInstructionView.h"

@interface WPReadingViewController ()<WPReadingViewDelegate,WPReadingViewCollectionViewCellVCDelegate,WPReadingViewCollectionViewChargeCellVCDelegate,UIAlertViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)WPReadingView *readingView;
@property(nonatomic,strong)UIView *windowView;
@property(nonatomic,strong)UIButton *coverBtn;

@property(nonatomic,strong)WPTitleView *titleView;
@property(nonatomic,assign)NSInteger indexPage;

@property(nonatomic,strong)WPReadingSecondCollectionViewCell *secondCollectionViewCell;
@property(nonatomic,strong)WPReadingFirstCollectionViewCell *firstCollectionViewCell;

@property(nonatomic,assign)BOOL isReady;

@property(nonatomic,assign)int userGlod;
@property(nonatomic,assign)int recordgold;

@property(nonatomic,strong)WPMRModel *selectedModel;

@end

@implementation WPReadingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];

}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

-(void)setupUI
{
    self.indexPage = 0;
    
    WPReadingView *view = [WPReadingView new];
    self.readingView = view;
    
    [view.collectionView registerClass:[WPReadingViewCollectionViewCell class] forCellWithReuseIdentifier:@"WPReadingViewCollectionViewCell"];
    view.collectionView.delegate = self;
    view.collectionView.dataSource = self;
    
    view.delegate = self;
    
    [self.view addSubview:view];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view);
    }];
    
    self.titleView = view.titleView;
}

#pragma mark - UIALertView的代理方法
//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        WPMineLoginVC *vc = [WPMineLoginVC new];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
    }
}

#pragma mark - WPReadingViewCollectionViewCellVCDelegate的代理方法
-(void)invidialCaseCellDidClickWith:(WPReadingViewCollectionViewCellVC *)cell model:(WPMRModel *)model
{
//    if ([WPUserAccountViewModel sharedInstance].userLogin)
//    {
        //看过的数量
        NSString *url = @"record/readRecord.do";
        NSDictionary *dict = @{@"recordId":@(model.id)};
        self.selectedModel.readAmount = self.selectedModel.readAmount+1;
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
        self.hidesBottomBarWhenPushed = YES;
        WPReadingInvidialRanking *rirVC = [WPReadingInvidialRanking new];
        rirVC.model = model;
        [self.navigationController pushViewController:rirVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
//    }
//    else
//    {
//        
//        [[WPUserAccountViewModel sharedInstance] loginTipWith:^{
//            
//            WPMineLoginVC *vc = [WPMineLoginVC new];
//            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
//        }];
//    }
}

-(void)invidialCaseCellDidClickDiseaseWith:(WPReadingViewCollectionViewCellVC *)vc disease:(NSString *)disease
{
//    if ([WPUserAccountViewModel sharedInstance].userLogin)
//    {
        self.hidesBottomBarWhenPushed = YES;
        WPNewDiseaseInstructionView *rirVC = [WPNewDiseaseInstructionView new];
        rirVC.disease = disease;
        rirVC.isPush = YES;
        [self.navigationController pushViewController:rirVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
//    }
//    else
//    {
//        [[WPUserAccountViewModel sharedInstance] loginTipWith:^{
//            
//            WPMineLoginVC *vc = [WPMineLoginVC new];
//            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
//        }];
//    }
}

#pragma mark - WPReadingViewCollectionViewChargeCellVCDelegate

-(void)chargeCaseCellDidClickWith:(WPReadingViewCollectionViewChargeCellVC *)vc model:(WPMRModel *)model
{
    if ([WPUserAccountViewModel sharedInstance].userLogin)
    {
        self.selectedModel = model;
        
        NSString *url = @"record/getGoldNum.do";
        NSDictionary *dict = @{@"recordId":@(model.id)};
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if ([responseObject[@"result"] isEqualToString:@"success"])
            {
                if ([responseObject[@"detail"][@"status"] intValue])
                {
                    
                    NSString *url = @"record/readRecord.do";
                    NSDictionary *dict = @{@"recordId":@(self.selectedModel.id)};
                    
                    self.selectedModel.readAmount = self.selectedModel.readAmount+1;
                    
                    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                        
                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        
                    }];
                    
                    
                    self.hidesBottomBarWhenPushed = YES;
                    WPReadingInvidialRanking *rirVC = [WPReadingInvidialRanking new];
                    rirVC.model = model;
                    [self.navigationController pushViewController:rirVC animated:YES];
                    self.hidesBottomBarWhenPushed = NO;
                }
                else
                {
                    self.recordgold = [responseObject[@"detail"][@"recordGold"] intValue];
                    self.userGlod = [responseObject[@"detail"][@"userGold"] intValue];
                    
                    [self showGoldInfomation];
                }
            }
            else
            {
                //            考虑到账号过期的情况
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    [self illegalLoginWithSuccessBlock:^{
                        
                        WPMineLoginVC *vc = [WPMineLoginVC new];
                        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                    }];
                }
                else
                {
                    [self showErrorInfoWithStatus:@"网络错误"];
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self showErrorInfoWithStatus:@"网络错误"];
        }];

    }
    else
    {
        [[WPUserAccountViewModel sharedInstance] loginTipWith:^{

            WPMineLoginVC *vc = [WPMineLoginVC new];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
        }];
        
    }
}

-(void)chargeCaseCellDidClickDiseaseWith:(WPReadingViewCollectionViewChargeCellVC *)vc disease:(NSString *)disease
{
    if ([WPUserAccountViewModel sharedInstance].userLogin)
    {
        self.hidesBottomBarWhenPushed = YES;
        WPNewDiseaseInstructionView *rirVC = [WPNewDiseaseInstructionView new];
        rirVC.disease = disease;
        [self.navigationController pushViewController:rirVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    }
    else
    {
        [[WPUserAccountViewModel sharedInstance] loginTipWith:^{
            
            WPMineLoginVC *vc = [WPMineLoginVC new];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
        }];
    }
}

#pragma mark - readingView的collectionView的代理方法

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 2;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WPReadingViewCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPReadingViewCollectionViewCell" forIndexPath:indexPath];
    //    移除上一个控制器
    [cell.tvc.view removeFromSuperview];
    
    if (indexPath.item == 0)
    {
        WPReadingViewCollectionViewCellVC *tvc = [WPReadingViewCollectionViewCellVC new];
        //    传递控制器
        cell.tvc = tvc;
        tvc.delegate = self;
        //    如果一个控制器的View作为另一个控制器的子控件那么这个控制器也应该作为另一个控制器的子控制器
        [self addChildViewController:tvc];
    }
    else
    {
        WPReadingViewCollectionViewChargeCellVC *tvc = [WPReadingViewCollectionViewChargeCellVC new];
        //    传递控制器
        cell.tvc = tvc;
        tvc.delegate = self;
        
        //    如果一个控制器的View作为另一个控制器的子控件那么这个控制器也应该作为另一个控制器的子控制器
        [self addChildViewController:tvc];
    }
    
    return cell;
}

#pragma mark - collectionView的滚动代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger index = (scrollView.contentOffset.x+SCREEN_WIDTH*0.5)/SCREEN_WIDTH;
    if (index == self.indexPage) {
        
        return ;
    }
    
    self.indexPage = index;
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    WPReadingTitleViewType type = (self.indexPage == 0)?WPReadingTitleViewTypeIndival:WPReadingTitleViewTypeFamous;
    [self.titleView moveSliderWith:type];
}

-(void)showGoldInfomation
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.coverBtn = coverBtn;
    coverBtn.frame = [UIScreen mainScreen].bounds;
    coverBtn.backgroundColor = RGBA_COLOR(51, 51, 51, 0.5);
    [coverBtn addTarget:self action:@selector(coverBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [window addSubview:coverBtn];
    
    UIView *windowView = [UIView new];
    self.windowView = windowView;
    windowView.layer.cornerRadius = 6;
    windowView.layer.masksToBounds = YES;
    windowView.backgroundColor = [UIColor whiteColor];
    [window addSubview:windowView];
    
    [windowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(window).offset(47);
        make.right.equalTo(window).offset(-47);
        make.height.mas_equalTo(295);
        make.top.equalTo(window).offset(186*K_SCALE_FULL);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textColor = GLobalFontColor;
    titleLabel.text = @"确认购买";
    [titleLabel sizeToFit];
    [windowView addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(windowView).offset(26);
        make.centerX.equalTo(windowView);
    }];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"chaBtn"] forState:UIControlStateNormal];
    [windowView addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(coverBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [cancelBtn sizeToFit];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(windowView).offset(8);
        make.right.equalTo(windowView).offset(-8);
    }];
    
    UILabel *goodsLabel = [UILabel new];
    goodsLabel.font = [UIFont systemFontOfSize:14];
    goodsLabel.textColor = GLobalFontColor;
    goodsLabel.text = @"购买物件：电子病历";
    [goodsLabel sizeToFit];
    [windowView addSubview:goodsLabel];
    
    [goodsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(windowView).offset(35);
        make.top.equalTo(titleLabel.mas_bottom).offset(26);
    }];
    
    NSString *purchasePriceStr = [NSString stringWithFormat:@"购买价格：%zd医票",self.recordgold];
    NSMutableAttributedString *purchasePrice = [[NSMutableAttributedString alloc] initWithString:purchasePriceStr];
    [purchasePrice addAttributes:@{NSForegroundColorAttributeName:GlobalColor} range:[purchasePriceStr rangeOfString:[NSString stringWithFormat:@"%zd医票",self.recordgold]]];
    
    UILabel *purchasePriceLabel = [UILabel new];
    purchasePriceLabel.font = [UIFont systemFontOfSize:14];
    purchasePriceLabel.textColor = GLobalFontColor;
    purchasePriceLabel.attributedText = purchasePrice;
    [purchasePriceLabel sizeToFit];
    [windowView addSubview:purchasePriceLabel];
    
    [purchasePriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(goodsLabel);
        make.top.equalTo(goodsLabel.mas_bottom).offset(20);
    }];
    
    
    NSString *currentGoldStr = [NSString stringWithFormat:@"当前医票：%zd医票",self.userGlod];
    NSMutableAttributedString *currentGoldAtt = [[NSMutableAttributedString alloc] initWithString:currentGoldStr];
    [currentGoldAtt addAttributes:@{NSForegroundColorAttributeName:GlobalColor} range:[currentGoldStr rangeOfString:[NSString stringWithFormat:@"%zd医票",self.userGlod]]];
    
    UILabel *currentGlodLabel = [UILabel new];
    currentGlodLabel.font = [UIFont systemFontOfSize:14];
    currentGlodLabel.textColor = GLobalFontColor;
    currentGlodLabel.attributedText = currentGoldAtt;
    [currentGlodLabel sizeToFit];
    [windowView addSubview:currentGlodLabel];
    
    [currentGlodLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(purchasePriceLabel);
        make.top.equalTo(purchasePriceLabel.mas_bottom).offset(20);
    }];
    
    NSString *title = (self.recordgold > self.userGlod) ? @"医票不足，请充值" : @"确认购买";
    UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [okBtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
    [okBtn setBackgroundImage:[UIImage imageNamed:@"highLight"] forState:UIControlStateHighlighted];
    [okBtn addTarget:self action:@selector(okBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [okBtn setTitle:title forState:UIControlStateNormal];
    okBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [windowView addSubview:okBtn];
    
    [okBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(windowView).offset(19);
        make.right.equalTo(windowView).offset(-19);
        make.top.equalTo(currentGlodLabel.mas_bottom).offset(26);
        make.height.mas_equalTo(40);
    }];
    
    UILabel *tipLabel = [UILabel new];
    tipLabel.text = @"病历购买后将置入病历收藏里";
    tipLabel.textColor = GloballightFontColor;
    tipLabel.font = [UIFont systemFontOfSize:13];
    [tipLabel sizeToFit];
    [windowView addSubview:tipLabel];
    
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(windowView);
        make.top.equalTo(okBtn.mas_bottom).offset(15);
    }];
}

-(void)okBtnDidClick
{
    if (self.recordgold <= self.userGlod)
    {
        //        通知阅读量
        NSString *url = @"record/readRecord.do";
        NSDictionary *dict = @{@"recordId":@(self.selectedModel.id)};
        
        self.selectedModel.readAmount = self.selectedModel.readAmount+1;
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if([responseObject[@"result"] isEqualToString:@"success"])
            {
                [self coverBtnDidClick];
                
                [self showSuccessInfoWithStatus:@"付费成功"];
                
                self.hidesBottomBarWhenPushed = YES;
                WPReadingInvidialRanking *rirVC = [WPReadingInvidialRanking new];
                rirVC.model = self.selectedModel;
                [self.navigationController pushViewController:rirVC animated:YES];
                self.hidesBottomBarWhenPushed = NO;
            }
            else
            {
                //            考虑到账号过期的情况
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    [self illegalLoginWithSuccessBlock:^{
                        
                        WPMineLoginVC *vc = [WPMineLoginVC new];
                        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                    }];
                }
                else
                {
                    [self showErrorInfoWithStatus:@"付费失败,请稍后重试"];
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self showErrorInfoWithStatus:@"网络错误"];
            
        }];
    }
    else
    {
//        跳转到购买金币界面
        [self coverBtnDidClick];
        
        //        调到购买金币界面去购买金币
        self.hidesBottomBarWhenPushed = YES;
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WPGoldCoinVC" bundle:nil];
        WPCoinTopUp *gcVC = [sb instantiateViewControllerWithIdentifier:@"goldTopUp"];
        [self.navigationController pushViewController:gcVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        
//        重新比较一下金币数量
        gcVC.backBlock = ^
        {
            [self chargeCaseCellDidClickWith:nil model:self.selectedModel];
        };
    }
}

-(void)coverBtnDidClick
{
 
    [self.windowView removeFromSuperview];
    [self.coverBtn removeFromSuperview];
    
    self.windowView = nil;
    self.coverBtn = nil;
}

#pragma mark - searchView的代理方法
-(void)WPReadingViewDidClickSearchBtn:(WPReadingView *)readingView
{
    [self presentViewController:[[WPPanNavigationController alloc] initWithRootViewController:[WPSearchVC new]] animated:NO completion:nil];
}

-(void)collectionViewCellBeCreated:(WPReadingView *)readingView
{
    self.firstCollectionViewCell = self.readingView.firstCollectionViewCell;
    
    self.firstCollectionViewCell.loadAgainBlock = ^()
    {
        
    };
    self.secondCollectionViewCell = self.readingView.secondCollectionViewCell;
    
    self.secondCollectionViewCell.loadAgainBlock = ^()
    {
       
    };
}
@end
